'use strict';

const https = require('https');
const url = require('url');
const fs = require('fs');
const config = require('../config');
const _ = require('lodash');
const FormData = require('form-data');
const logger = require('log4js').getLogger();

const QQMail = module.exports = function () {
	if (!(this instanceof QQMail)) {
		return new QQMail();
	}
	this.isOK = false;
	this.urlString = '';
	
	this.initialize();
};

QQMail.prototype.initialize = function () {
	if (!config.cookie) return;
	this.urlString = `https://doc.weixin.qq.com/txdoc/imgupload`;
	return this.isOK = true;
};

QQMail.prototype.postFormData = function (formData, callback) {
  const options = url.parse(this.urlString);
  options.method = 'POST';
  options.headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",
    "Cookie": config.cookie
  };
  options.headers['Content-Type'] = formData.getHeaders()['content-type'];
  function next() {
    if (!callback) return;
    callback.apply(null, arguments);
    callback = void 0;
  };
  const req = https.request(options, res => {
    res.setEncoding('utf8');
    var data = '';
    res.on('data', d => data += d);
    res.on('end', () => next(null, data));
  });
  req.on('error', err => next(err));
  req.setTimeout(60000, () => {
    req.abort();
    return next(new Error('POST timeout'));
  });
  return formData.pipe(req);
};

QQMail.prototype.uploadFile = function (filePath, callback) {
	const formData = new FormData();
	formData.append('file', fs.createReadStream(filePath), { filename: 'blob', contentType: 'image/png' });
	return this.postFormData(formData, callback);
};

QQMail.prototype.parseNewUrl = function (data) {
	if (!data || typeof data !== 'string') return;
	const result = data.match(/{"url":"(.+)"}/);
	if (!result || !result[1]) logger.error(data);
	return result && result[1];
};

if (require.main === module) (function () {
	const tsFile = process.argv[2];
	if (!tsFile) return logger.error('Missing tsFile !!!');
	const uploader = QQMail();
	if (!uploader.isOK) return logger.error('Uploader: not isOK !!!');
	return uploader.uploadFile(tsFile, (err, data) => {
		logger.debug(err, data);
		if (!err) logger.debug(uploader.parseNewUrl(data));
	});
})();

